package com.by.cloud.controller;

import com.by.cloud.annotation.PreAuthorize;
import com.by.cloud.common.BaseResponse;
import com.by.cloud.common.PageResult;
import com.by.cloud.common.ResultUtils;
import com.by.cloud.enums.UserRoleEnum;
import com.by.cloud.exception.BusinessException;
import com.by.cloud.exception.ErrorCode;
import com.by.cloud.exception.ThrowUtils;
import com.by.cloud.model.dto.picture.PicturePageRequest;
import com.by.cloud.model.dto.picture.PictureReviewRequest;
import com.by.cloud.model.dto.picture.PictureUpdateDto;
import com.by.cloud.model.dto.picture.PictureUploadRequest;
import com.by.cloud.model.vo.picture.PictureCategoryTagVo;
import com.by.cloud.model.vo.picture.PictureVo;
import com.by.cloud.service.PictureService;
import com.by.cloud.utils.CosManager;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * @author linweirui
 * @date 2024/12/13 9:58
 */
@RestController
@RequestMapping("/picture")
@Api(tags = "图片模块")
@Slf4j
public class PictureController {
    @Resource
    private CosManager cosManager;
    @Resource
    private PictureService pictureService;

    @ApiOperation("测试初始图片上传")
    @PostMapping("/test/upload")
    @PreAuthorize(role = UserRoleEnum.ADMIN)
    public BaseResponse<String> testUploadFile(@RequestPart("file") MultipartFile multipartFile) {
        // 文件目录
        String filename = multipartFile.getOriginalFilename();
        String filepath = String.format("/test/%s", filename);
        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(filepath, null);
            multipartFile.transferTo(file);
            cosManager.putObject(filepath, file);
            // 返回可访问地址
            return ResultUtils.success(filepath);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            if (file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, filepath = {}", filepath);
                }
            }
        }
    }

    @ApiOperation("测试初始图片下载")
    @GetMapping("/test/download/")
    @PreAuthorize(role = UserRoleEnum.ADMIN)
    public void testDownloadFile(String filepath, HttpServletResponse response) throws IOException {
        COSObjectInputStream cosObjectInput = null;
        try {
            COSObject cosObject = cosManager.getObject(filepath);
            cosObjectInput = cosObject.getObjectContent();
            // 处理下载到的流
            byte[] bytes = IOUtils.toByteArray(cosObjectInput);
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filepath);
            // 写入响应
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("file download error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
        } finally {
            if (cosObjectInput != null) {
                cosObjectInput.close();
            }
        }
    }

    @ApiOperation("图片上传")
    @PostMapping("/upload")
    public BaseResponse<PictureVo> uploadPicture(
            @RequestPart("file") MultipartFile file,
            PictureUploadRequest uploadRequest) {
        PictureVo pictureVo = pictureService.uploadPicture(file, uploadRequest);
        return ResultUtils.success(pictureVo);
    }

    @ApiOperation("根据图片id查询图片信息")
    @GetMapping("/getPictureInfo/{picId}")
    public BaseResponse<PictureVo> getPictureInfoByPicId(@PathVariable Long picId) {
        ThrowUtils.throwIf(picId == null || picId <= 0, ErrorCode.PARAMS_ERROR);
        PictureVo pictureVo = pictureService.getPictureVoById(picId);
        return ResultUtils.success(pictureVo);
    }

    @ApiOperation("根据图片id删除图片")
    @PreAuthorize(role = UserRoleEnum.ADMIN)
    @DeleteMapping("/delete/{picId}")
    public BaseResponse<Boolean> delPictureById(@PathVariable Long picId) {
        ThrowUtils.throwIf(picId == null || picId <= 0, ErrorCode.PARAMS_ERROR);
        boolean isSuccess = pictureService.removeById(picId);
        return ResultUtils.success(isSuccess);
    }

    @ApiOperation("更新图片信息")
    @PreAuthorize(role = UserRoleEnum.ADMIN)
    @PutMapping("/update")
    public BaseResponse<Boolean> updatePictureInfo(@RequestBody PictureUpdateDto updateDto) {
        ThrowUtils.throwIf(updateDto == null, ErrorCode.PARAMS_ERROR);
        boolean isSuccess = pictureService.updatePictureById(updateDto);
        return ResultUtils.success(isSuccess);
    }

    @ApiOperation("分页查询图片信息")
    @PostMapping("/page")
    public BaseResponse<PageResult<PictureVo>> queryPictureByPage(@RequestBody PicturePageRequest picturePageRequest) {
        PageResult<PictureVo> pictureVoList = pictureService.queryPictureByPage(picturePageRequest);
        return ResultUtils.success(pictureVoList);
    }

    @ApiOperation("查询图片分类标签")
    @GetMapping("/tag_category")
    public BaseResponse<PictureCategoryTagVo> listPictureCategoryTag() {
        PictureCategoryTagVo pictureCategoryTagVo = pictureService.listPictureCategoryTag();
        return ResultUtils.success(pictureCategoryTagVo);
    }

    @ApiOperation("审核用户上传图片")
    @PostMapping("/review")
    @PreAuthorize(role = UserRoleEnum.ADMIN)
    public BaseResponse<Boolean> reviewByPictureId(@RequestBody PictureReviewRequest reviewRequest) {
        boolean isSuccess = pictureService.reviewByPictureId(reviewRequest);
        return ResultUtils.success(isSuccess);
    }
}

